<template>
    <div>
        <div id="fullpage">
            <div class="section section-gallery" id="section0">
                <div class="swiper-wrapper">
                    <div class="slide" id="slide1"></div>
                    <div class="slide" id="slide2"></div>
                    <div class="slide" id="slide3"></div>
                    <div class="slide" id="slide4"></div>
                    <div class="slide" id="slide5"></div>
                </div>
            </div>
            <div class="section" id="section1">
                <div class="theme">
                    <ul class="alias">
                        <li class="p">
                            <div class="name"></div>
                            <span style="font-size: 60px;">{{bridegroom}}</span>
                            <!--                            <img alt="P" src="../assets/images/theme_p.png"/>-->
                        </li>
                        <li class="and">
                            <img alt="&" src="../assets/images/theme_and.png"/>
                        </li>
                        <li class="m">
                            <span style="font-size: 60px;">{{bride}}</span>
                            <!--                            <img alt="P" src="../assets/images/theme_m.png"/>-->
                        </li>
                    </ul>
                    <div class="slagon">
                        <img alt="Infinity" src="../assets/images/theme_infinity.png"/>
                    </div>
                    <div class="thanks">
                        <p class="hr"></p>
                        <span>感谢您参加我们的婚礼！</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="wish-board" id="wish-board" ref="wish-board"></div>
    </div>
</template>

<script>
    import CommentManager from 'src/assets/js/comment';
    import FullPage from 'src/assets/js/fullpage';
    import 'src/assets/styles/fullpage.css';

    const wsuri = "ws://" + document.location.hostname + ":8080/wedding";


    export default {
        name: "index",
        data() {
            return {
                websocket: null,
                wishes: [],
                cm: null,
                stopped: false,
                speed: 4000,
                duration: 1000,
                pendingMsg: [],
                ws: null,
                fp: null,
                galleryInterval: null,
                bridegroom: 'xy',
                bride: 'xx',
                weddingId: null
            }
        },
        destroyed() {
            //页面销毁时关闭长连接
            // this.websocketclose();
        },
        mounted() {
            this.initConfig();
            this.initFullpage();
            this.initBullet();
        },
        methods: {
            initFullpage() {
                this.fp = new FullPage('#fullpage', {
                    // anchors: ['gallery', 'theme'],
                    // afterLoad: this.afterLoad,
                    controlArrows: false,
                    autoScrolling: true,
                    scrollHorizontally: true,
                    sectionsColor: ['#C63D0F', '#1BBC9B', '#7E8F7C'],
                    navigation: true,
                    navigationPosition: 'right',
                    navigationTooltips: ['First page', 'Second page', 'Third and last page']
                });
            },
            initBullet() {
                this.cm = new CommentManager(this.$refs['wish-board']);
                this.cm.init();
                this.cm.start();
                this.loop();
            },
            initConfig() {
                this.$resource('/api/config', null, null, {emulateJSON: true}).get().then(res => {
                    this.bridegroom = res.data.bridegroom;
                    this.bride = res.data.bride;
                    this.weddingId = res.data.id;
                    this.initWebSocket();
                }, e => {
                    this.$message({
                        message: '获取配置信息失败！',
                        type: 'error'
                    });
                });
            },
            afterLoad(origin) {
                const that = this;
                clearInterval(this.galleryInterval);
                switch (origin.anchor) {
                    case 'gallery':
                        this.galleryInterval = setInterval(function () {
                            that.fp.moveSlideRight();
                        }, 4000);
                        break;
                    case 'theme':
                        break;
                    default:
                        break;
                }
            },
            initWebSocket() {
                this.websocket = new WebSocket(wsuri + "/" + this.weddingId);
                this.websocket.onopen = this.websocketonopen;
                this.websocket.onerror = this.websocketonerror;
                this.websocket.onmessage = this.websocketonmessage;
                this.websocket.onclose = this.websocketclose;
            },
            websocketonopen() {
                this.$message({
                    message: 'WebSocket 连接成功！',
                    type: 'success'
                });
                console.log("WebSocket 连接成功！");
            },
            websocketonerror(e) {
                this.$message({
                    duration: 0,
                    message: 'WebSocket 连接发生错误！',
                    type: 'error'
                });
                console.error("WebSocket连接发生错误", e);
            },
            websocketonmessage(e) {
                let msg = JSON.parse(e.data);
                this.push(msg);
            },
            // websocketsend(agentData) {
            //     this.websocket.send(agentData);
            // },
            websocketclose(e) {
                this.$message({
                    duration: 0,
                    message: 'WebSocket 连接已关闭！',
                    type: 'warning'
                });
                console.warn("connection closed");
            },
            push(ws) {
                this.wishes = this.wishes.concat(ws);
            },
            unshift(ws) {
                this.wishes = ws.concat(this.wishes);
            },
            pause() {
                this.stopped = true;
                this.cm.stop();
            },
            loop() {
                if (this.stopped) {
                    return;
                }
                let msg;
                while ((msg = this.pendingMsg.shift())) {
                    this.publish(msg);
                }
                msg = this.wishes.shift();
                if (msg) {
                    this.publish(msg);
                    // this.wishes.push(msg);
                }
                setTimeout(() => {
                    this.loop();
                }, this.duration);
            },
            publish(msg) {
                let cmt = {
                    mode: 1,
                    size: 16,
                    dur: Math.floor(Math.random() * 4000 + this.speed)
                };
                let color = this.str2rgb('').join(',');
                cmt.text = '<span class="icon">' + '<img src="' + msg.headImgUrl.replace(/\/0$/, '/96') + '">' +
                    '</span><span class="text" style="background:rgba(' + color + ',0.4)">' +
                    (msg.nickname + '：') + msg.content + '</span>';
                this.cm.send(cmt);
            },
            str2rgb(str) {
                let hash = 0;
                for (let i = 0; i < str.length; i++) {
                    hash = str.charCodeAt(i) + ((hash << 5) - hash);
                }
                let colour = [];
                for (let i = 0; i < 3; i++) {
                    let value = (hash >> (i * 8)) & 0xFF;
                    colour.push(value);
                }
                return colour;
            }
        }
    }
</script>
<style scoped>

</style>
